package com.rinlink.jbcodec.creator;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rinlink.jbcodec.JSONCodec;
import com.rinlink.jbcodec.context.ObjectToBytesCreatorContext;
import com.rinlink.jbcodec.exception.AttributePropertyException;
import com.rinlink.jbcodec.exception.CreateTransformException;
import com.rinlink.jbcodec.exception.FieldValueException;
import com.rinlink.jbcodec.transform.Transform;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


public abstract class ListToBytesCreator<T> extends ObjectToBytesCreator<JSONArray> {

    private Class<T> itemJavaClass;
    public ListToBytesCreator(){
        Type type = getClass().getGenericSuperclass();
        ParameterizedType ptype=(ParameterizedType)type;
        Type[] types = ptype.getActualTypeArguments();
        this.itemJavaClass = (Class<T>) types[0];
    }

    @Override
    public Transform<byte[]> create(int fieldIndex, ObjectToBytesCreatorContext ctx) {
        JSONCodec.Field field = ctx.getScheme().getFields().get(fieldIndex);
        JSONObject sourceData = (JSONObject) ctx.getSourceData();
        JSONObject attr = field.getAttr();
        String fieldName = field.getName();
        JSONArray value;
        try {
           value = sourceData.getJSONArray(fieldName);
        }catch (ClassCastException e){
            throw new CreateTransformException("类型不匹配");
        }
        return create(value,attr == null ? new JSONObject() : attr, sourceData);
    }

    @Override
    protected Transform<byte[]> create(JSONArray objects, JSONObject attr, JSONObject source) {
        String list_size_field = attr.getString("list_size_field");
        if (list_size_field == null)
            throw new AttributePropertyException("list_size_field");

        Integer list_size = source.getInteger(list_size_field);
        if (list_size == null)
            throw new AttributePropertyException("list_size_field");

        if (objects.size() != list_size)
            throw new FieldValueException();

        List<T> list = objects.toJavaList(itemJavaClass);
        return create(list,attr,source);
    }


    protected abstract Transform<byte[]> create(List<T> ts, JSONObject attr, JSONObject source);



}
